const { cartModel } = require('../../models/carts')
const { goodsModel } = require('../../models/goods')


// 购物车
module.exports = class Carts {
  // 添加购物车商品
  static async addCartsGood(ctx) {
    let { count, good_id, state, checked } = ctx.request.body;

    if (!count && !good_id) {
      ctx.body = { status: 300, msg: "有未填项" }
      return;
    }
    // 获取用户id
    let user_id = ctx.token;

    // 查找是否是同一个商品
    let bool = await cartModel.find({ good_id });
    let data = null;
    if (bool.length) {
      // 是同一款商品
      data = await cartModel.updateOne({ _id: bool[0]._id }, { $set: { count: bool[0].count + count } })
    } else {
      data = await cartModel.insertMany({ count, user_id, good_id, state, checked })
    }
    // 是否添加成功
    if ((data.n == 1 && data.ok == 1) || data.length)
      ctx.body = { status: 200, msg: '添加成功' }
    else
      ctx.body = { status: 200, msg: '添加失败' }
  }
  // 查找购物车商品
  static async getCartsGood(ctx) {
    let userid = ctx.token;

    if (!userid) {
      ctx.body = { status: 300, msg: '未传入token' }
      return;
    }

    let data = await cartModel.find({ user_id: userid });
    data = JSON.parse(JSON.stringify(data));

    if (data.length) {
      // 获取商品信息
      for (let i = 0; i < data.length; i++) {
        let good = await goodsModel.find({ _id: data[i].good_id }, { swiperImg: 0, detail: 0 });
        data[i]['good_data'] = good[0];
      }
    }

    if (data.length) ctx.body = { status: 200, msg: "查询成功", data }
    else ctx.body = { status: 400, msg: "查询失败", data }
  }
  // 修改购物车商品
  static async updateCartsGood(ctx) {
    let { cart_id, count, checked } = ctx.request.body;

    // 判断是修改状态还是数量
    let iso = count ? ['count', count] : ['checked', checked]

    // 要修改的值
    let params = {
      [iso[0]]: iso[1]
    }
    let bool = await cartModel.updateOne({ _id: cart_id }, { $set: params })

    if (bool.n && bool.ok)
      ctx.body = { status: 200, msg: '修改成功' }
    else
      ctx.body = { status: 400, msg: '修改失败' }

  }
  // 删除购物车商品
  static async deletCartsGood(ctx) {
    let id = ctx.request.body.id;
    let bool = await cartModel.deleteMany({_id:id})
    console.log(bool)

    if (bool.n && bool.ok) {
      ctx.body={status:200,msg:'删除成功'}
    } else {
      ctx.body={status:400,msg:'删除失败'}
    }
  }
}